<template>
  <div class="my-tag">
    <input
      v-if="isEdit"
      v-focus
      ref="inp"
      class="input"
      type="text"
      placeholder="输入标签"
      :value="value"
      @keyup.enter="handleEnter"
      @blur="isEdit = false"
    >
    <div
      v-else
      @dblclick="handleClick"
      class="text"
    >{{ value }}</div>
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: String
    }
  },
  data() {
    return {
      isEdit: false
    }
  },
  methods: {
    handleEnter(e) {
      if (e.target.value.trim() === '') {
        return alert('标签内容不能为空')
      }
      // console.log(e.target)
      // 子传父,回车时将输入框的内容提交给父组件更新
      this.$emit('input', e.target.value)
      // 提交完成,关闭输入状态
      this.isEdit = false
    },
    handleClick() {
      // 双击切换到显示状态
      this.isEdit = true
      // 等dom更新完, 立即获取焦点
      // this.$nextTick(() => {
      //   this.$refs.inp.focus()
      // })
    }
  },
}
</script>

<style lang="less" scoped>
// npm install less less-loader
.my-tag {
  cursor: pointer;
  .input {
    appearance: none;
    outline: none;
    border: 1px solid #ccc;
    width: 100px;
    height: 40px;
    box-sizing: border-box;
    padding: 10px;
    color: #666;
    &::placeholder {
      color: #666;
    }
  }
}
</style>